package com.terren.schelude.work;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;

import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import com.terren.common.util.CommonUtil;
import com.terren.common.util.LogUtil;
import com.terren.config.SysConfig;
import com.terren.db.service.OpinionAnalysisService;

public class BasicWork {
	protected Logger log = LogUtil.getLogger(getClass());
	protected CountDownLatch countDownLatch;
	protected OpinionAnalysisService opinionAnalysisService;
	protected Set<String> set;
	public BasicWork(){
		opinionAnalysisService = CommonUtil.getBean(OpinionAnalysisService.class);
		set = getKeywords();
	}
	
	protected Integer getScore(String text) {
		Integer score = -1;//默认获取score失败
		try {
			JsonRpcHttpClient client_sent = new JsonRpcHttpClient(new URL(SysConfig.RPC_URL));
			Map<String, String> headers = new HashMap<String, String>();
			headers.put("Rpc-Type", "shop");
			client_sent.setHeaders(headers);
			String scoreStr = client_sent.invoke("getSentiment",new Object[]{text},String.class);   //长文本
			//String score8 = client_sent.invoke("getSentimentRnn",new Object[]{text},String.class); //短文本
			score = Integer.parseInt(scoreStr);
			log.info("接口调用成功：score = "+scoreStr);
			
		}catch(Throwable e) {
			log.error("get content's score fail,content= " + text + ",error info:"+ e);
		}
		return score;
	}
	
	protected Set<String> getKeywords() {
		List<String> strList = new ArrayList<String>();
		try {
			strList = opinionAnalysisService.getKeywords();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return filterKeyword(strList);
	}
	
	protected Set<String> filterKeyword(List<String> strList){
		Set<String> sets = new HashSet<String>();
		for(String str : strList) {
			if(str.contains(" ")) {
				String[] temp = str.split(" ");
				for(String tempStr : temp) {
					if(!tempStr.contains("借点钱")) {
						sets.add(tempStr);
					}
				}
			}	
		}
		return sets;
	}
	
	protected boolean findKeyword(String content,Set<String> set) {
		boolean flag = false;
		Iterator<String> urlIt = set.iterator();
		while(urlIt.hasNext()) {
			if(content.contains(urlIt.next())) {
				flag = true;
				break;
			}
		}
		if(flag) {
			log.info("************符合条件************");
		}
		return flag;
	}
	
}
